class UserController < ApplicationController

  include ApplicationHelper
  
  before_filter :protect, :except => [:login, :register]
  
  def index
    @title = "Ruutr Spaces User Page"
  end

  def register
    @title = "Register"
    if request.post? and params[:user]
      #logger.info params[:user].inspect
      #raise params[:user].inspect
      @user = User.new(params[:user])
      if @user.save
        flash[:notice] = "User #{@user.screen_name} created!"
        @user.login!(session)
        redirect_to_next_page     
      else
        flash[:notice] = "Something has gone wrong and we were unable to register you. Please try again later."         
      end
    end
  end

  def login
    @title = "Log in to Ruutr.com"
    if request.post? and params[:user]
      #logger.info params[:user].inspect}
      #raise params[:user].inspect
      @user = User.new(params[:user])
      user = User.find_by_screen_name_and_password(@user.screen_name, @user.password)
      if user
        flash[:notice] = "Welcome back #{@user.screen_name}!"
        user.login!(session)
        if @user.remember_me == "1"
          cookies[:remember_me] = { :value => "1", :expires => 10.years.from_now }
        end
        redirect_to_next_page
      else
        @user.password = nil
        flash[:notice] = "Invalid screen name & password combination."
      end
    end
  end
  
  def logout
    session[:user_id] = nil
    flash[:notice] = "You've successfully loggged out"
    redirect_to :action => "index", :controller => "site"
  end
  
  private
  
  def protect
    unless logged_in?
      session[:protected_page] = request.request_uri
      flash[:notice] = "Please log in first."
      redirect_to :action => "login"
      return false
    end
  end
  
  def redirect_to_next_page
    if (next_url = session[:protected_page])
      redirect_to next_url
      session[:protected_page] = nil
    else
      redirect_to :action => "index"
    end    
  end
  
end
